package com.song.boot.springstudy.myspring.customcontext;

import lombok.var;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * 需求：假设我们需要在所有标注了 @Service 注解的 Bean 实例化前，强制设置它们的作用域为 prototype（默认是 singleton）
 */
public class CustomApplicationContext extends AnnotationConfigApplicationContext {
    @Override
    protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        // 调用父类的默认处理（必须保留）
        super.postProcessBeanFactory(beanFactory);
        
        // 遍历所有Bean定义
        String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
        // BeanDefinition userServiceDefinition = beanFactory.getBeanDefinition("userService");
        // System.out.println(userServiceDefinition.getScope());
        for (String beanName : beanDefinitionNames) {
            // 获取Bean定义元数据
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);

            // 检查Bean对应的类是否标注了@Configuration
            try {
                Class<?> beanClass = Class.forName(beanDefinition.getBeanClassName());
                if (beanClass.isAnnotationPresent(org.springframework.context.annotation.Configuration.class)) {
                    // todo 强制设置作用域为prototype
                    beanDefinition.setScope("prototype");
                    System.out.println("已将Bean [" + beanName + "] 的作用域改为 prototype");
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}